package cn.jiaqiang.chatgpt.data.infrastructure.repository;

import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.UserAccountEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.valobj.UserAccountStatusVO;
import cn.jiaqiang.chatgpt.data.domain.openai.repository.IOpenAiRepository;
import cn.jiaqiang.chatgpt.data.infrastructure.dao.IUserAccountDao;
import cn.jiaqiang.chatgpt.data.infrastructure.dao.IUserModelDao;
import cn.jiaqiang.chatgpt.data.infrastructure.po.UserAccountPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.ThreadPoolExecutor;


/**
 * Created with IntelliJ IDEA.
 * Description: openAi 仓储, 实现 domain 层的 IOpenAiRepository
 * User: 86187
 * Date: 2024-04-02
 * Time: 16:58
 */
@Slf4j
@Repository
public class OpenAiRepository implements IOpenAiRepository {
    private final ThreadPoolExecutor threadPoolExecutor;
    private final IUserAccountDao userAccountDao;
    public final IUserModelDao userModelDao;
    public OpenAiRepository(ThreadPoolExecutor threadPoolExecutor, IUserAccountDao userAccountDao, IUserModelDao userModelDao) {
        this.threadPoolExecutor = threadPoolExecutor;
        this.userAccountDao = userAccountDao;
        this.userModelDao = userModelDao;
    }

    /**
     * 查询用户账户信息
     * @param userId 用户唯一标识
     * @return 用户账户实体,返回给前端的实体
     */
    @Override
    public UserAccountEntity queryUserAccount(String userId) {
        // 查询信息
        UserAccountPO userAccountPO = userAccountDao.queryUserAccountWithUserId(userId);
        if (userAccountPO == null) {
            return null;
        }
        // 对象转换并返回
        return UserAccountEntity
                .builder()
                .userId(userAccountPO.getUserId())
                .openid(userAccountPO.getOpenid())
                .userAccountStatusVO(UserAccountStatusVO.getInfo(userAccountPO.getStatus()))
                .surplusQuota(userAccountPO.getSurplusQuota())
                .totalQuota(userAccountPO.getTotalQuota())
                .build();
    }

    @Override
    @Transactional
    public void subAccountQuota(String userId, String model) {

        threadPoolExecutor.execute(() -> {
            log.info("异步更新开户用户 openid: {} 模型: {} 使用额度, ThreadId = {}", userId, model, Thread.currentThread().getId());
            userModelDao.subAccountQuota(userId, model);
            userAccountDao.subAccountQuota(userId);
        });
    }
}
